#Author: 0x9DEFA478


TargetIP=""
TargetUser=""
TargetGDBServerPort=""
TargetSSHServerPort=""
ExecPathLocal=""
ExecPathRemote=""

options=$(getopt -o a --long TargetIP:,TargetUser:,TargetGDBServerPort:,TargetSSHServerPort:,ExecPathLocal:,ExecPathRemote: -n $0 -- "$@")
if (( $? != 0 )); then
  exit 1
fi
eval set -- "${options}"
while true
do
  case $1 in
    --TargetIP)
      TargetIP=$2
      shift 2
    ;;
    --TargetUser)
      TargetUser=$2
      shift 2
    ;;
    --TargetGDBServerPort)
      TargetGDBServerPort=$2
      shift 2
    ;;
    --TargetSSHServerPort)
      TargetSSHServerPort=$2
      shift 2
    ;;
    --ExecPathLocal)
      ExecPathLocal=$2
      shift 2
    ;;
    --ExecPathRemote)
      ExecPathRemote=$2
      shift 2
    ;;
    --)
      shift
      break
    ;;
    *)
      echo "$0 param decode error $1"
      exit 1
    ;;
  esac
done


if [[ $TargetIP == "" ]]; then
  echo "\e[31mTargetIP no set!\e[0m"
  exit 1
fi
if [[ $TargetUser == "" ]]; then
  echo "\e[31mTargetUser no set!\e[0m"
  exit 1
fi
if [[ $TargetGDBServerPort == "" ]]; then
  echo "\e[31mTargetGDBServerPort no set!\e[0m"
  exit 1
fi
if [[ $ExecPathLocal == "" ]]; then
  echo "\e[31mExecPathLocal no set!\e[0m"
  exit 1
fi
if [[ $ExecPathRemote == "" ]]; then
  echo "\e[31mExecPathRemote no set!\e[0m"
  exit 1
fi


SSHArgs="-o StrictHostKeyChecking=no "

if [[ $TargetSSHServerPort != "" ]]; then
  SSHArgs="-P ${TargetSSHServerPort}"
fi

ExecName=$(basename $ExecPathRemote)


ssh ${SSHArgs} ${TargetUser}@${TargetIP} "killall ${ExecName}"
ssh ${SSHArgs} ${TargetUser}@${TargetIP} "ProcPID=\$(ss -tlnp | grep LISTEN | grep ${TargetGDBServerPort} | sed -n 's/.*pid=\([0-9]\+\).*/\1/p') && if [[ \$ProcPID != \"\" ]]; then echo kill \$ProcPID;kill \$ProcPID; else echo no process Port: ${TargetGDBServerPort}; fi"

scp ${SSHArgs} ${ExecPathLocal} ${TargetUser}@${TargetIP}:${ExecPathRemote}
if (( $? != 0 )); then
  exit 2
fi

ssh ${SSHArgs} ${TargetUser}@${TargetIP} "chmod +x ${ExecPathRemote}"
if (( $? != 0 )); then
  exit 3
fi

